import os
import pandas as pd
import numpy as np
import tensorflow as tf
from tensorflow.keras.models import load_model
from datetime import datetime
from sklearn.preprocessing import StandardScaler
from sklearn.metrics import mean_absolute_error, mean_squared_error, r2_score

# 加载模型
model = load_model('model_2/trained_model.h5')

# 读取CSV文件
df = pd.read_csv('data_test.csv')

# 将时间列转换为时间戳
df['time'] = df['time'].apply(lambda x: datetime.strptime(x, '%Y-%m-%d %H:%M:%S').timestamp())

# 分离特征和标签
X = df[['value', 'time']].values  # 特征数据
y = df['value'].values  # 标签数据

# 数据标准化
scaler = StandardScaler()  # 初始化StandardScaler对象
X_scaled = scaler.fit_transform(X)  # 对特征数据进行标准化

# 假设我们已经有了测试集
X_test, y_test = X_scaled[:100], y[:100]  # 示例：取前100条数据作为测试集

# 评估模型
loss = model.evaluate(X_test, y_test)
print(f"Test loss: {loss}")

# 进行预测
predictions = model.predict(X_test)

# 计算评估指标
mae = mean_absolute_error(y_test, predictions)
mse = mean_squared_error(y_test, predictions)
r2 = r2_score(y_test, predictions)

# 输出预测结果及评估指标

print("\nPredictions:")
for i, pred in enumerate(predictions):
    error = abs(pred[0] - y_test[i])
    print(f"Sample {i+1}: Predicted Value = {pred[0]:.4f}, True Value = {y_test[i]:.4f}, Error = {error:.4f}")

'''
MAE 和 MSE 的值都非常小，这表明模型的预测误差很小，即模型在预测时与真实值之间的差距很小。
R² 接近于 1，这意味着模型几乎完美地拟合了数据，即模型具有很高的解释力和预测能力
'''
print("\nEvaluation Metrics:")
print(f"Mean Absolute Error (MAE): {mae}")
print(f"Mean Squared Error (MSE): {mse}")
print(f"R-squared (R2): {r2}")
